package com.azt.front.action.freemarker;

import com.azt.api.pojo.Company;
import com.azt.api.pojo.CompanyInfo;
import com.azt.api.pojo.Role;
import com.azt.api.service.CompanyService;
import com.azt.front.utils.ContextUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 前台顶部
 * */
@Component("front_head")
public class HeadDirective implements TemplateDirectiveModel {

    @Autowired
    private CompanyService companyService;

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body)
            throws TemplateException, IOException {
        Map parmap = new HashMap();

        //判断是否可以切换角色
        boolean canSwitch = false;
        List<Role> roleList = ContextUtil.getRoles();
        if(CollectionUtil.isNotEmpty(roleList) && roleList.size() > 1) {
            Integer currentRoleType = ContextUtil.getCurrentRoleType();
            for(Role role : roleList) {
                if(currentRoleType != null && role.getRoleType() != null && currentRoleType.intValue() != role.getRoleType().intValue()) {
                    canSwitch = true;
                }
            }
        }
        parmap.put("canSwitch", canSwitch);

        if(ContextUtil.getCompanyId() != null) {
            CompanyInfo companyInfo = companyService.getCompanyInfoByCompanyId(ContextUtil.getCompanyId());
            parmap.put("companyInfo", companyInfo);
            Company topCompany = companyService.getTopParentCompany(ContextUtil.getCompanyId());
        	parmap.put("topCompany", topCompany);
        }
        

        DirectiveUtils.writer(parmap, env, params, body);
    }

}
